/**
 * 招聘需求，详情页
 */
import React from 'react';
import { Col, Row, Tabs, Spin } from 'antd';
import { PageContainer } from '@/molecules';
import AuthComponent from '@/utils/auth/AuthComponent';
import { useRequest, defaultFormatResult } from '@/hooks';
import { history } from 'umi'
import { connect } from 'umi';
import helper from '@/utils/auth/helper';
import ResumeList from '@/pages/Recruitment/Resume/List';
import CandidateList from '@/pages/Recruitment/Candidate/List';
import InterviewList from '@/pages/Recruitment/Interview/List';
import HireList from '@/pages/Recruitment/Hire/List';
import { eventTrack } from '@/utils/track';
import { sameTabProps } from '@/utils/tab';
import { Icon } from '../components';

import useChannelDict from '../useChannelDict';
import {
    DemandAccept,
    DemandAssign,
    DemandBrief,
    DemandChangeStatus,
    DemandDetail,
    DemandEdit,
    DemandPublish
} from '../containers';
import styles from './index.less';
import { getDemand, getCountsByRecruitId } from '../service';

const { checkCode } = helper;
const defaultCounts = {
    applyNum: 0,
    candidateNum: 0,
    entryNum: 0,
    hireNum: 0,
    interviewNum: 0,
    recruitNumFromTalent: 0,
    recruitNum: 0
};
const auth = [
    checkCode('office:recruitment:course:requirement'), // 需求
    checkCode('office:recruitment:course:resume'), // 简历
    checkCode('office:recruitment:course:candidate'), // 人才
    checkCode('office:recruitment:course:interview'), // 面试
    checkCode('office:recruitment:course:hire') // 录用
];
function Detail({ location, user }) {
    const { query } = location;
    const { currentUser = {} } = user;
    const { id } = query;
    const { data = {}, loading, run } = useRequest(() => getDemand(id));
    // 当前登录人是否为招聘负责人
    const isPrincipal = React.useMemo(() => data?.data?.principalEmployeeCode === currentUser?.employeeCode, [
        data,
        currentUser
    ]);
    // 当前登录人是否为招聘发起人
    const isLauncher = React.useMemo(() => data?.data?.launchEmployeeCode === currentUser?.employeeCode, [
        data,
        currentUser
    ]);
    // 数量
    const { data: counts = { ...defaultCounts }, run: refreshCounts } = useRequest(
        () => {
            if (data?.data?.id) return getCountsByRecruitId(data?.data?.id);
            return Promise.resolve({ code: 10000, data: { ...defaultCounts } });
        },
        {
            refreshDeps: [data?.data?.id],
            ...defaultFormatResult
        }
    );

    // 渠道列表
    const { channelDict = [] } = useChannelDict(true);

    const [lastQuery, setLastQuery] = React.useState({});
    const activeKey = React.useMemo(() => {
        if (!query.activeKey) {
            return `${auth.findIndex(_ => _) + 1}`;
        }
        return query.activeKey;
    }, [query.activeKey]);

    /**
     * 数据流转
     */
    const handleDataExchange = React.useCallback(() => {
        refreshCounts();
    }, []);

    /**
     * 跳转新增简历
     */
    const handleJumpResumeAdd = React.useCallback(() => {
        if (!data?.data) {
            return;
        }
        const { recruitCode, dutyCode, dutyName, organizationCode, organizationName, companyCode } = data?.data;
        history.push({
            pathname: '/office/personnelManagement/recruitment/resume/record/apply',
            query: { resumeId: id, recruitCode, dutyCode, dutyName, organizationCode, organizationName, companyCode }
        });
    }, [data?.data]);

    if (loading) {
        return (
            <Row type="flex" justify="center" style={{ padding: 32 }}>
                <Spin />
            </Row>
        );
    }

    const handleTabChange = key => {
        refreshCounts();
        setLastQuery({ [activeKey]: { ...query } });

        history.push({
            query: {
                id,
                ...lastQuery[key],
                activeKey: key
            },
            ...sameTabProps
        });
    };
    return (
        <PageContainer>
            <Row type="flex" justify="space-between" style={{ marginBottom: 24 }}>
                <Col span={14}>
                    <DemandBrief data={data?.data} />
                </Col>
                <div style={{ display: 'flex' }}>
                    <AuthComponent code="office:recruitment:course:resume:add">
                        <Icon
                            button
                            title="录入简历"
                            type="listfunction_readyinterview_icon_default"
                            onClick={() => {
                                eventTrack({
                                    eventName: 'personnel_management_recruitment_demand_list_detail_resume_enter_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        click_context: data.dutyName
                                    }
                                });
                                handleJumpResumeAdd();
                            }}
                        />
                    </AuthComponent>
                    {data?.data?.recruitStatus === 2 && (
                        <div style={{ marginLeft: 8 }}>
                            <DemandAccept
                                data={data?.data}
                                onSuccess={() => {
                                    run();
                                }}
                                button
                            />
                        </div>
                    )}
                    {[2, 3].includes(data?.data?.recruitStatus) && (
                        <div style={{ marginLeft: 8 }}>
                            <DemandAssign
                                data={data?.data}
                                onSuccess={() => {
                                    run();
                                }}
                                button
                            />
                        </div>
                    )}
                    {data?.data?.recruitStatus === 3 && (
                        <div style={{ marginLeft: 8 }}>
                            <DemandChangeStatus
                                data={data?.data}
                                button
                                onSuccess={() => {
                                    run();
                                }}
                            />
                        </div>
                    )}
                    <div style={{ marginLeft: 8 }}>
                        <DemandPublish button data={data?.data} />
                    </div>
                    <div style={{ marginLeft: 8 }}>
                        <DemandEdit button data={data?.data} />
                    </div>
                </div>
            </Row>
            {auth.some(_ => _) && (
                <Tabs
                    type="card"
                    className={styles.tabs}
                    activeKey={activeKey}
                    onChange={handleTabChange}
                    onTabClick={key => {
                        const eventMap = {
                            1: 'personnel_management_recruitment_demand_list_detail_require_click',
                            2: 'personnel_management_recruitment_demand_list_detail_resume_click',
                            3: 'personnel_management_recruitment_demand_list_detail_candidate_click',
                            4: 'personnel_management_recruitment_demand_list_detail_interview_click',
                            5: 'personnel_management_recruitment_demand_list_detail_offer_click'
                        };
                        eventTrack({
                            eventName: eventMap[key],
                            pageName: 'personnel_management_recruitment',
                            eventProps: {
                                click_context: data.dutyName
                            }
                        });
                    }}
                >
                    {auth[0] && (
                        <Tabs.TabPane tab={`需求(${counts.recruitNum || 0})`} key="1">
                            <DemandDetail data={data.data} style={styles.demand} />
                        </Tabs.TabPane>
                    )}
                    {auth[1] && (
                        <Tabs.TabPane tab={`简历(${counts.resumeNum || 0})`} key="2">
                            {activeKey === '2' && (
                                <ResumeList
                                    isLauncher={isLauncher}
                                    isPrincipal={isPrincipal}
                                    recruitCode={data?.data?.recruitCode}
                                    onJumpAdd={handleJumpResumeAdd}
                                    onDataExchange={handleDataExchange}
                                    channelDict={channelDict}
                                    recruitDetail={data.data}
                                ></ResumeList>
                            )}
                        </Tabs.TabPane>
                    )}
                    {auth[2] && (
                        <Tabs.TabPane tab={`候选(${counts.candidateNum || 0})`} key="3">
                            {activeKey === '3' && (
                                <CandidateList
                                    isPrincipal={isPrincipal}
                                    isLauncher={isLauncher}
                                    recruitCode={data?.data?.recruitCode}
                                    onDataExchange={handleDataExchange}
                                    channelDict={channelDict}
                                    recruitDetail={data.data}
                                ></CandidateList>
                            )}
                        </Tabs.TabPane>
                    )}
                    {auth[3] && (
                        <Tabs.TabPane tab={`面试(${counts.interviewNum || 0})`} key="4">
                            {activeKey === '4' && (
                                <InterviewList
                                    isLauncher={isLauncher}
                                    isPrincipal={isPrincipal}
                                    recruitCode={data?.data?.recruitCode}
                                    onDataExchange={handleDataExchange}
                                ></InterviewList>
                            )}
                        </Tabs.TabPane>
                    )}
                    {auth[4] && (
                        <Tabs.TabPane tab={`录用(${counts.hireNum || 0})`} key="5">
                            {activeKey === '5' && (
                                <HireList
                                    isLauncher={isLauncher}
                                    isPrincipal={isPrincipal}
                                    recruitCode={data?.data?.recruitCode}
                                    onDataExchange={handleDataExchange}
                                ></HireList>
                            )}
                        </Tabs.TabPane>
                    )}
                </Tabs>
            )}
        </PageContainer>
    );
}

export default connect(({ user }) => ({ user }))(Detail);
